package cn.com.pusai.core.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

// Referenced classes of package cn.com.ecinc.core.util:
//			ByteUtil

public class SecurityUtil {

	public SecurityUtil() {
	}

	public static byte[] md5(byte input[]) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			return md5.digest(input);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}

	}

	public static byte[] md5(String input) {
		try {
			return md5(input.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {

			throw new RuntimeException(e);
		}
	}

	public static String md5Hex(byte input[]) {
		return ByteUtil.byteToHex(md5(input));
	}

	public static String md5Hex(String input) {
		try {
			return md5Hex(input.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String desEncryptHex(String input, String secretKey)
	{
		try{
		if (secretKey.length() != secretKey.getBytes().length || secretKey.length() != 8)
			throw new IllegalArgumentException("密钥得由8个单字节字符(英文字母,数字,标点符号等)组成.");
		Cipher cipher;
		DESKeySpec key = new DESKeySpec(secretKey.getBytes());
		javax.crypto.SecretKey skey = SecretKeyFactory.getInstance("DES").generateSecret(key);
		cipher = Cipher.getInstance("DES");
		cipher.init(1, skey);
		return ByteUtil.byteToHex(cipher.doFinal(input.getBytes("UTF-8")));
		}catch(Exception e){
			throw new RuntimeException(e);
			
		}
	}

	public static String desDecryptString(String inputHex, String secretKey)
	{
		try{
		if (secretKey.length() != secretKey.getBytes().length || secretKey.length() != 8)
			throw new IllegalArgumentException("密钥得由8个单字节字符(英文字母,数字,标点符号等)组成.");
		Cipher cipher;
		DESKeySpec key = new DESKeySpec(secretKey.getBytes());
		javax.crypto.SecretKey skey = SecretKeyFactory.getInstance("DES").generateSecret(key);
		cipher = Cipher.getInstance("DES");
		cipher.init(2, skey);
		return new String(cipher.doFinal(ByteUtil.hexToByte(inputHex)), "UTF-8");
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
